package org.travel_system.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.travel_system.pojo.Evaluation;
import org.travel_system.utils.Result;
import org.travel_system.service.EvaluationService;
import org.travel_system.service.UserService;
import org.travel_system.utils.ThreadLocalUtil;

import java.util.List;
import java.util.Map;

@Controller
@RestController
@RequestMapping("/evaluations")
public class EvaluationController {

    private final UserService userService;
    private final EvaluationService evaluationService;

    @Autowired
    public EvaluationController(EvaluationService evaluationService,UserService userService) {
        this.evaluationService = evaluationService;
        this.userService = userService;
    }

    //查询评价列表
    @GetMapping
    public Result<List<Evaluation>> getEvaluations() {

        //获取当前登录用户的id
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        Integer userId = userService.findUserId(username);
        //根据当前登录用户的id查询评价列表
        return Result.success(evaluationService.getEvaluations(userId));
    }

    //根据id查询评价
    @GetMapping("/{id}")
    public Result<Evaluation> getEvaluationById(@PathVariable int id) {
        return Result.success(evaluationService.getEvaluationById(id));
    }

    //添加评价
    @PostMapping
    public Result<?> addEvaluation(@RequestBody Evaluation evaluation) {
        //获取当前登录用户的id
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        Integer userId = userService.findUserId(username);
        evaluation.setTouristId(userId);
        return evaluationService.addEvaluation(evaluation) > 0 ?
                Result.success() :
                Result.error("添加评价失败");
    }

    //删除评价
    @DeleteMapping
    public Result<?> deleteEvaluationById(@RequestParam int id) {
       return evaluationService.deleteEvaluationById(id) > 0 ?
               Result.success() :
               Result.error("删除评价失败");
    }
}
